﻿using mars_server.csharp.dao;
using mars_server.csharp.dao.impl;
using mars_server.csharp.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace mars_server.csharp.AO.impl
{
    public class UserGroupAOImpl : UserGroupAO
    {
        private UserGroupAOImpl() { }
        private static readonly UserGroupAOImpl instance = new UserGroupAOImpl();

        public static UserGroupAOImpl Instance
        {
            get
            {
                return instance;
            }
        }

        UserGroupManager userGroupManager = UserGroupManagerImpl.Instance;

        UserAO userAOImpl = UserAOImpl.Instance;

        UserManager userManager = UserManagerImpl.Instance;

        GroupManager groupManager = GroupManagerImpl.Instance;


        public List<UserDO> queryUserDOsByGroupId(long groupId)
        {
            List<UserDO> UserDOs = new List<UserDO>();
            List<UserGroupDO> userGroupDOs = userGroupManager.selectUserGroupDOsByGroupId(groupId);
            List<long> userIds = new List<long>();
            foreach(UserGroupDO userGroupDO in userGroupDOs)
            {
                userIds.Add(userGroupDO.userId);
            }
            UserDOs = userManager.selectUserDOsByUserIds(userIds);
            return UserDOs;
        }

        public long addUserGroupDO(string groupName, List<long> userIds)
        {
            Dictionary<string, string> sqlMap = new Dictionary<string, string>();
            sqlMap.Add("group_name", groupName);
            List<GroupDO> groupDOs = groupManager.selectGroupDOByQuery(sqlMap);
            if (groupDOs.Count == 0 || groupDOs[0].id == 0)
            {
                return 0;
            }
            long groupId = groupDOs[0].id;
            foreach(long userId in userIds)
            {
                UserGroupDO userGroup = new UserGroupDO();
                userGroup.userId = userId;
                userGroup.GroupId = groupId;
                userGroupManager.insertUserGroupDO(userGroup);
                Console.WriteLine("[info]|-向群：" + groupId + "【添加用户】"+userId);
            }
            return groupId;
           
        }

        public List<long> getGroupIdsByUserId(long userId)
        {
            List<UserGroupDO> userGroupDOs = userGroupManager.selectGroupDOsByUserId(userId);
            List<long> groupIds = new List<long>();
            foreach(UserGroupDO userGroupDO in userGroupDOs)
            {
                groupIds.Add(userGroupDO.GroupId);
            }
            return groupIds;
        }
    }
}
